package procuctconsumer;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Print2{
   Lock lock =new ReentrantLock();
   Condition c1 =lock.newCondition();
   Condition c2 =lock.newCondition();
   Condition c3 =lock.newCondition();
   volatile int numer =1;

   public void printC1(int j)  {
       lock.lock();
       try {
           while (numer !=1){
               c1.await();
           }
           System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
           for (int i=1;i<=5;i++){
               System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
           }
           numer=2;
           c2.signal();
       }catch (Exception exception){
           exception.printStackTrace();
       }finally {
           lock.unlock();
       }
   }

   public void printC2(int j) {
       lock.lock();
       try {
           while (numer !=2){
               c2.await();
           }
           System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
           for (int i=1;i<=10;i++){
               System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
           }
           numer=3;
           c3.signal();
       }catch (Exception exception){
           exception.printStackTrace();
       }finally {
           lock.unlock();
       }
   }

   public void printC3(int j) {
       lock.lock();
       try {
           while (numer !=3){
               c3.await();
           }
           System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
           for (int i=1;i<=15;i++){
               System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
           }
           numer=1;
           c1.signal();
       }catch (Exception exception){
           exception.printStackTrace();
       }finally {
           lock.unlock();
       }
   }
}

public class condition2 {




    public static void main(String[] args) {
        Print2 print =new Print2();

        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC1(i);
            }
        },"c1").start();

        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC2(i);
            }
        },"c2").start();


        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC3(i);
            }
        },"c3").start();
    }
}
